import os, sys, commands, calendar, pytz, datetime

# convert localtime to utctime
def _Localtime2Utc(tstr):
    """
    >>> _Localtime2Utc('2017-07-31 16:00:00')
    '1501545600'
    """

    fmt = '%Y-%m-%d %H:%M:%S'
    time_zone = pytz.timezone('Asia/Shanghai')
    local_time = datetime.datetime.strptime(tstr, fmt)
    utc_time  = time_zone.localize(local_time)
    return utc_time.strftime('%s')


# calculate traffic out by 95
def CalcTrafficout(rrd, start_time, end_time):
    """
    >>> CalcTrafficout('test.rrd', '2017-07-31 16:00:00', '2017-08-31 16:00:00')
    (0, '356678.53911')
    """

    start = _Localtime2Utc(start_time)
    end = _Localtime2Utc(end_time)
    tmp = datetime.datetime.utcfromtimestamp(float(start))
    billing95 = int(12*24*calendar.monthrange(tmp.year, tmp.month)[1]*0.05 + 1.5)
    ret, out = commands.getstatusoutput("\
        rrdtool fetch %s AVERAGE --start %s --end %s \
        | sed \'1,2d\' \
        | awk \'{print $2}\'" % (rrd, start, end)
    )

    if ret == 0:
        traffic_out = out.split('\n')
        return (0, str(sorted(map(lambda f:float(f), traffic_out), reverse=True)[billing95]))
    else:
        return (1, '')

if __name__ == "__main__":
    import doctest
    doctest.testmod()
